package com.study.thymeleaf.core;

import com.alibaba.fastjson.JSON;
import lombok.Data;
import lombok.experimental.Accessors;

import java.io.Serializable;
import java.util.Objects;

/**
 * 返回数据
 */
@Data
@Accessors(chain = true)
public class R<T> implements Serializable {

    private static final long serialVersionUID = 1L;

    private Integer code;

    private boolean success;

    private String msg;

    private T data;


    private R(ResultCode resultCode) {
        this.code = resultCode.getCode();
        this.msg = resultCode.getMsg();
    }

    private R(ResultCode resultCode, String msg) {
        this.code = resultCode.getCode();
        this.msg = msg;
    }

    private R(int code, String msg) {
        this.code = code;
        this.msg = msg;
    }

    public static R<Void> noAuth() {
        return error(SystemCodeEnum.SYSTEM_NO_AUTH);
    }

    public static <T> R<T> error(ResultCode resultCode) {
        return new R<>(resultCode);
    }

    public static R<Void> error(int code, String msg) {
        return new R<>(code, msg);
    }

    public static R<Void> error(ResultCode resultCode, String msg) {
        return new R<>(resultCode, msg);
    }

    public static <T> R<T> ok(T data) {
        R<T> result = new R<>(SystemCodeEnum.SYSTEM_OK);
        result.setData(data);
        result.setSuccess(true);
        return result;
    }

    public static R<Object> ok() {
        R<Object> result = new R<>(SystemCodeEnum.SYSTEM_OK);
        result.setSuccess(true);
        return result;
    }

    @Override
    public String toString() {
        return JSON.toJSONString(this);
    }
}
